<template>
    <view class="home-wrap u-m-b-20" :style="{background: '#f8f8f8 url('+API_URL()+'images/login_bg.png) no-repeat','background-size': '100%'}">
        <shopro-navbar :isBack="false" :background="{background:'url('+API_URL()+'\'images/login_bg.png\') no-repeat','background-size': '100% 100%'}">
            <text
                slot="content"
                style="color: #000; width: 100%; text-align: center;padding-left: 20rpx;color:#fff"
            >
                智慧体育
            </text>
        </shopro-navbar>
        <view class="login-wrap form-wrap  safe-area-inset-bottom" @tap.stop
              style="border-radius: 20rpx 20rpx 0 0;">
            <view class="u-flex u-row-center u-col-center u-flex-col">
                <view class="u-flex" style="width: 140rpx;height: 140rpx;">
                    <image style="width: 100%;height: 100%;" :src="API_URL()()+'images/logo.jpg'"></image>
                </view>
                <view class="name u-m-t-30 u-flex u-row-center u-m-b-20" style="width: 100%; text-align: center;font-size: 40rpx;font-weight: bold">
                    <view :class="isxuesheng=='1'?'font-green':''" @click="clearshuju('1')">学生登录</view>
                    <view :class="isxuesheng=='2'?'font-green':''"  style="margin-left: 30rpx" @click="clearshuju('2')">老师登录</view>
                </view>
            </view>
            <!-- 1.账号密码登录 -->
            <view>
                <view class="form-item">
                    <view class="item-content u-flex u-col-center">
                        <u-input class="u-m-r-10 u-flex-1" placeholder="请输入账号" @blur="checkValue($event, 'account')"
                                 @input="checkValue($event, 'account')" :placeholderStyle="placeholderStyle"
                                 v-model="form['accountLogin'].data.account" type="text"></u-input>
                    </view>
                    <view class="message-error">
                        {{ form["accountLogin"].error.account || "" }}
                    </view>
                </view>
                <view class="form-item">
                    <view class="item-content u-flex u-col-center">
                        <u-input class="u-m-r-10 u-flex-1" placeholder="请输入密码" :placeholderStyle="placeholderStyle"
                                 v-model="form['accountLogin'].data.password" type="password"
                                 @blur="checkValue($event, 'password')" @input="checkValue($event, 'password')"></u-input>
                    </view>
                    <view class="message-error">
                        {{ form["accountLogin"].error.password || "" }}
                    </view>
                </view>
                <button class="u-reset-button login-btn-start" @tap="accountLoginSubmit">
                    确认登录
                </button>
            </view>
            <!-- 协议 -->
            <view
                class="agreement-box u-flex u-row-left u-m-b-60">
                <u-checkbox v-model="protocol" shape="circle" active-color="#3FA897">
                    <view class="agreement-text tcp-text u-flex u-col-center">
                        登录即代表阅读并同意
                        <view class="tcp-text u-flex u-col-center">
                            <view @tap.stop="jump('/pages/user/userxieyi')">
                                《用户协议》
                            </view>
                            与
                            <view @tap.stop="jump('/pages/user/yinsi')">
                                《隐私协议》
                            </view>
                        </view>
                    </view>
                </u-checkbox>
            </view>
            <!-- 第三方登录 -->


        </view>
    </view>
</template>

<script>
/**
 * 登录提示页
 */
import FormValidate from "@/shopro/validate/form";
import schema from "@/uview-ui/libs/util/async-validator";
import wechat from "@/shopro/wechat/wechat";
import {mapActions, mapGetters} from "vuex";
import { API_URL } from '@/env.js'

export default {
    name: "shoproAuthModal",
    data() {
        return {
            isxuesheng:'1',
            platform: this.$platform.get(),
            device: this.$platform.device(),
            form: {
                // 1.账号密码登录
                accountLogin: {
                    data: {
                        type    : "1",
                        account : "", // 账号
                        password: "" // 密码
                    },
                    rules: {
                        account: FormValidate.account,
                        password: FormValidate.password
                    },
                    error: {
                        account: "",
                        password: ""
                    }
                },

                // 2.短信登录
                smsLogin: {
                    data: {
                        mobile: "", // 手机号
                        code: "", // 验证码
                        isMobileEnd: false // 手机号输入完毕
                    },
                    rules: {
                        code: FormValidate.code,
                        mobile: FormValidate.mobile
                    },
                    error: {
                        mobile: "", // 手机号
                        code: "" // 验证码
                    }
                },
                // 3.注册
                register: {
                    data: {
                        mobile: "", // 手机号
                        code: "", // 验证码
                        password: "", // 密码
                        isMobileEnd: false // 手机号输入完毕
                    },
                    rules: {
                        code: FormValidate.code,
                        mobile: FormValidate.mobile,
                        password: FormValidate.password
                    },
                    error: {
                        mobile: "", // 手机号
                        code: "", // 验证码
                        password: "" // 密码
                    }
                },

                // 4.忘记密码
                forgotPwd: {
                    data: {
                        mobile: "", //手机号
                        code: "", //验证码
                        password: "", //密码
                        isMobileEnd: false // 手机号输入完毕
                    },
                    rules: {
                        mobile: FormValidate.mobile,
                        code: FormValidate.code,
                        password: FormValidate.password
                    },
                    error: {
                        mobile: "", //手机号
                        code: "", //验证码
                        password: "" //密码
                    }
                },
                // 5.绑定手机号
                bindMobile: {
                    data: {
                        mobile: "", //手机号
                        code: "", //验证码
                        isMobileEnd: false // 手机号输入完毕
                    },
                    rules: {
                        code: FormValidate.code,
                        mobile: FormValidate.mobile
                    },
                    error: {
                        mobile: "", //手机号
                        code: "" //验证码
                    }
                },
                // 6.修改密码
                changePwd: {
                    data: {
                        oldPassword: "", //旧密码
                        newPassword: "", //新密码
                        reNewPassword: "" //确认密码
                    },
                    rules: {
                        oldPassword: FormValidate.password,
                        newPassword: FormValidate.password,
                        reNewPassword: [
                            {
                                required: true,
                                message: "请重新输入密码",
                                trigger: ["change", "blur"]
                            },
                            {
                                validator: (rule, value, callback) => {
                                    return value === this.form.changePwd.data.newPassword;
                                },
                                message: "两次输入的密码不一致",
                                trigger: ["change", "blur"]
                            }
                        ]
                    },
                    error: {
                        oldPassword: "", //旧密码
                        newPassword: "", //新密码
                        reNewPassword: "" //确认密码
                    }
                }
            },
            codeText: "获取验证码",
            disabledCode: false,
            protocol: false, //是否同意隐私协议
            placeholderStyle: "font-size: 30rpx; font-weight: 500;color:#C2C7CF;",
            authType:'accountLogin'
        };
    },

    computed: {
        ...mapGetters(["initShop", "isLogin"]),
    },
    mounted() { },
    methods: {
        // 路由跳转
        jump(path, parmas) {
            this.$Router.push({
                path : path,
                query: parmas
            });
        },
        API_URL() {
            return API_URL
        },
        ...mapActions(["getUserInfo", "showAuthModal"]),

        // 检测
        checkValue(e, key) {
            this.validation(key);
        },
        clearshuju(val) {
            this.isxuesheng                      = val;
            this.form.accountLogin.data.type     = val;
            this.form.accountLogin.data.account  = "";
            this.form.accountLogin.data.password = "";
        },
        // 校验数据
        validation(key, callback = () => { }) {
            let that = this;
            //拿到需要校验的数据
            let fieldValue = this.form[this.authType].data[key];
            //拿到需要检验的规则
            let rules = this.form[this.authType].rules[key];
            // 判空
            if (!rules || rules.length === 0) {
                return callback("");
            }
            // 设置当前的装填，标识为校验中
            let validateState = "validating";
            // 调用async-validator的方法
            let validator = new schema({
                [key]: rules
            });
            // 校验
            validator.validate(
                {
                    [key]: fieldValue
                },
                {
                    firstFields: true
                },
                (errors, fields) => {
                    // 记录状态和报错信息
                    validateState = !errors ? "success" : "error";
                    let validateMessage = errors ? errors[0].message : "";
                    that.form[that.authType].error[key] = validateMessage;
                    callback(validateMessage);
                }
            );
        },

        // 校验全部数据
        validateAll(callback) {
            let that = this;
            return new Promise(resolve => {
                // 对当前所有表单检验
                let valid = true; // 默认通过
                let count = 0; // 用于标记是否检查完毕
                let errorArr = []; // 存放错误信息
                let curFormData = that.form[that.authType].data;
                Object.keys(curFormData).map(field => {
                    that.validation(field, error => {
                        // 如果回调有error
                        if (error) {
                            valid = false;
                            errorArr.push(error);
                        }
                        if (++count === Object.keys(curFormData).length) {
                            resolve(valid);
                            if (errorArr.length) {
                                this.$u.toast(errorArr[0]);
                            }
                            if (typeof callback == "function") callback(valid);
                        }
                    });
                });
            });
        },

        // 手机号是否输入完毕
        mobileInput(e, key) {
            this.form[this.authType].data.isMobileEnd = this.$u.test.mobile(
                this.form[this.authType].data.mobile
            );
            this.validation(key);
        },

        closeAuthModal() {
            this.$store.dispatch("showAuthModal", "");
        },

        // 获取短信验证码
        getSmsCode(type) {
            const that = this;
            if (that.form[this.authType].data.isMobileEnd && !that.disabledCode) {
                that.$http(
                    "common.smsSend",
                    {
                        mobile: that.form[this.authType].data.mobile,
                        event: type
                    },
                    "获取验证码中..."
                ).then(res => {
                    if (res.code === 1) {
                        that.codeChange();
                        that.$u.toast("验证码已发送，请注意查收短信");
                    } else {
                        that.$u.toast(res.msg);
                    }
                });
            } else {
                that.$u.toast("请稍后再试");
            }
        },

        // 倒计时
        codeChange() {
            if (this.disabledCode) return;
            this.disabledCode = true;
            let n = 60;
            this.codeText = n + "s";
            const run = setInterval(() => {
                n -= 1;
                if (n < 0) {
                    clearInterval(run);
                }
                this.codeText = n + "s";
                if (this.codeText < 0 + "s") {
                    this.disabledCode = false;
                    this.codeText = "重新获取";
                }
            }, 1000);
        },

        // 规则校验
        validateSubmit() {
            if (
                ["accountLogin", "smsLogin", "register"].includes(this.authType) &&
                !this.protocol
            ) {
                this.$u.toast("请同意用户协议");
                return false;
            }
            return this.validateAll();
        },

        // 第三方登录
        async thirdLogin(provider, payload = null) {
            if (this.platform === 'wxMiniProgram' && payload === null) return;
            if (!this.protocol) {
                this.$u.toast("请同意用户协议");
                return false;
            }
            const that = this;
            let token = "";
            console.log("===payload",payload)
            switch (provider) {
                case "wechat":
                    token = await wechat.login(payload);
                    break;
                case "alipay":
                    break;
                case "apple":
                    token = await apple.appleIdOauth();
                    break;
                default:
                    break;
            }
            if (token) {
                that.getUserInfo(token);
            }
        },

        // 1.账号登录
        async accountLoginSubmit() {
            let that = this;
            (await that.validateSubmit()) &&
            that
                .$http(
                    "login.wechatminilogin",
                    {
                        type    : that.form["accountLogin"].data.type,
                        username : that.form["accountLogin"].data.account.replace(/\s*/g, ""),
                        password: that.form["accountLogin"].data.password
                    },
                    "登录中..."
                )
                .then(res => {
                    if(res.code!='-1'){
                        console.log("===access_token",res.data.access_token)
                        that.getUserInfo(res.data.access_token);
                        that.$u.toast(res.msg);
                    }else {
                        that.$u.toast(res.msg);
                    }

                });
        },

        // 2.短信登录
        async smsLoginSubmit() {
            let that = this;
            (await that.validateSubmit()) &&
            that
                .$http(
                    "user.smsLogin",
                    {
                        mobile: that.form["smsLogin"].data.mobile,
                        code: that.form["smsLogin"].data.code
                    },
                    "登录中..."
                )
                .then(res => {
                    if (res.code === 1) {
                        that.closeAuthModal();
                        that.getUserInfo(res.data.token);
                        that.$u.toast(res.msg);
                    }
                });
        },

        // 3.注册
        async registerSubmit() {
            let that = this;
            (await that.validateSubmit()) &&
            that
                .$http(
                    "user.register",
                    {
                        mobile: that.form["register"].data.mobile,
                        code: that.form["register"].data.code,
                        password: that.form["register"].data.password
                    },
                    "注册中..."
                )
                .then(res => {
                    if (res.code === 1) {
                        that.$u.toast(res.msg);
                        that.closeAuthModal();
                        that.getUserInfo(res.data.token);
                    }
                });
        },

        // 4.忘记密码
        async forgotPwdSubmit() {
            let that = this;
            (await that.validateSubmit()) &&
            that
                .$http(
                    "user.forgotPwd",
                    {
                        mobile: that.form["forgotPwd"].data.mobile,
                        code: that.form["forgotPwd"].data.code,
                        password: that.form["forgotPwd"].data.password
                    },
                    "修改中..."
                )
                .then(res => {
                    if (res.code === 1) {
                        that.$u.toast(res.msg);
                        if (that.isLogin) {
                            that.closeAuthModal();
                        } else {
                            that.showAuthModal("accountLogin");
                        }
                    }
                });
        },

        // 5.绑定手机
        async bindMobileSubmit() {
            let that = this;
            (await that.validateSubmit()) &&
            that
                .$http(
                    "user.bindMobile",
                    {
                        mobile: that.form["bindMobile"].data.mobile,
                        code: that.form["bindMobile"].data.code,
                        password: that.form["bindMobile"].data.password
                    },
                    "绑定中..."
                )
                .then(res => {
                    if (res.code === 1) {
                        that.$u.toast(res.msg);
                        that.closeAuthModal();
                        that.getUserInfo();
                    }
                });
        },

        // 6.修改密码
        async changePwdSubmit() {
            let that = this;
            (await that.validateSubmit()) &&
            that
                .$http(
                    "user.changePwd",
                    {
                        oldpassword: that.form["changePwd"].data.oldPassword,
                        newpassword: that.form["changePwd"].data.newPassword
                    },
                    "修改中..."
                )
                .then(res => {
                    if (res.code === 1) {
                        that.closeAuthModal();
                        that.$u.toast(res.msg);
                        that.getUserInfo(res.data.userinfo.token);
                    }
                });
        }
    }
};
</script>

<style lang="scss" scoped>
page{
    overflow: hidden;
}
@keyframes title-animation {
    0% {
        font-size: 32rpx;
    }

    100% {
        font-size: 36rpx;
    }
}

.form-wrap {
    .form-item {

        display: flex;
        flex-direction: column;
        font-size: 28rpx;
        padding: 20rpx 0;
        color: #303133;
        box-sizing: border-box;
        line-height: 70rpx;
        width: 100%;
        background: #f5f5f5;
        border-radius: 20rpx;
        margin-top: 20rpx;
        padding: 10rpx 20rpx;
        border: 0;

        .item-title {
            width: 140rpx;
            font-size: 30rpx;
            color: #333;
            font-weight: 600;
            text-align: left;
        }

        .message-error {
            text-align: left;
            font-size: 24rpx;
            line-height: 24rpx;
            color: $u-type-error;
            margin-top: 12rpx;
            margin-left: 20rpx;
        }
    }
}

.login-wrap {
    padding: 50rpx 34rpx;
    height: 69vh;
    width: 91%;
    margin: 20px auto 0;
    background-color: #fff;

    .head-box {
        .head-title {
            min-width: 160rpx;
            font-size: 36rpx;
            font-weight: bold;
            color: #333333;
            line-height: 36rpx;
        }

        .head-title-active {
            width: 160rpx;
            font-size: 32rpx;
            font-weight: 600;
            color: #999;
            line-height: 36rpx;
        }

        .head-title-animation {
            animation-name: title-animation;
            animation-duration: 0.1s;
            animation-timing-function: ease-out;
            animation-fill-mode: forwards;
        }

        .head-title-line {
            position: relative;

            &::before {
                content: "";
                width: 1rpx;
                height: 34rpx;
                background-color: #e4e7ed;
                position: absolute;
                left: -30rpx;
                top: 50%;
                transform: translateY(-50%);
            }
        }

        .head-subtitle {
            font-size: 26rpx;
            font-weight: 400;
            color: #c2c7cf;
            text-align: left;
            display: flex;
        }
    }

    .code-btn[disabled] {
        background-color: #fff;
    }

    .code-btn-start {
        width: 160rpx;
        line-height: 56rpx;
        border: 1rpx solid #e9b766;
        border-radius: 28rpx;
        font-size: 26rpx;
        font-weight: 400;
        color: #e9b766;
        opacity: 0.5;
    }

    .forgot-btn {
        width: 160rpx;
        line-height: 56rpx;
        font-size: 30rpx;
        font-weight: 500;
        color: #999;
    }

    .code-btn-end {
        opacity: 1 !important;
    }

    .login-btn-start {
        width: 97%;
        margin: 80rpx auto;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 80rpx;
        background: linear-gradient(90deg, #3FA897, #3FA897);
        border-radius: 28rpx;
        font-size: 26rpx;
        font-weight: 500;
        color: #ffffff;
    }

    .type-btn {
        padding: 20rpx;
        margin: 40rpx auto;
        width: 200rpx;
        font-size: 30rpx;
        font-weight: 500;
        color: #999999;
    }

    .auto-login-box {
        width: 100%;

        .auto-login-img {
            width: 68rpx;
            height: 68rpx;
            border-radius: 50%;
            margin: 0 30rpx;
        }
    }

    .agreement-box {
        margin: 80rpx auto 0;

        .protocol-check {
            transform: scale(0.7);
        }

        .agreement-text {
            font-size: 24rpx;
            font-weight: 500;
            color: #999999;

            .tcp-text {
                color: #3FA897;
            }
        }
    }
}
.font-green{
    color:#3FA897;
    position: relative;
    &:after{
        position: absolute;
        content: "";
        width:  40rpx;
        height: 14rpx;
        background:#3FA897;
        left: 31%;
        top: 117%;
        border-radius: 18rpx;
    }
}
</style>
